/**
 * Created by Ysssssss on 2021/5/2.
 */

import React, { PureComponent } from 'react'
import PropTypes from 'prop-types';
import {CustomizeDndProvider, DraggableDiv} from "@common/presentational/DndSort";
import {moveToNewIndex} from "@utils/arrayHelper";
import {Button, Form, Input, Radio} from "antd";
import ImageUpload from "@common/presentational/ImageUpload";
import DoubleCheck from "@common/presentational/DoubleCheck";
import DateRangePicker from "@common/presentational/DateRangePicker";
import ProductChoose from "@components/shoppingMall/design/ProductChoose";
import {PLATFORM_MAP} from "@constants/PlatformList";
import {DesignTemplateContext} from "@pages/shoppingMall/ShoppingMallDesignDetailPage";

class BannerListModule extends PureComponent {
    static propTypes = {
        bannerInfo: PropTypes.object,
        index: PropTypes.number,
        onChange: PropTypes.func
    }

    constructor(props) {
        super(props);
        this.state = {
            createTag: false
        }

        this.bannerRef = {}
    }

    toggleCreateTag (value) {
        this.setState({
            createTag: value
        })
    }

    sortList (dragId, hoverId) {
        const { index, bannerInfo, onChange } = this.props
        const { bannerList } = bannerInfo
        let dragIndex = 0
        let hoverIndex = 0
        bannerList.forEach((item, i) => {
            if(item.name === dragId) {
                dragIndex = i
            }
            if(item.name === hoverId) {
                hoverIndex = i
            }
        })
        onChange && onChange(index, {
            ...bannerInfo,
            bannerList: moveToNewIndex(bannerList, dragIndex, hoverIndex)
        })
    }



    editSubmit (values, i) {
        const { onChange, bannerInfo, index } = this.props
        if (i < 0) {
            onChange && onChange(index, {
                ...bannerInfo,
                bannerList: [
                    ...bannerInfo.bannerList,
                    values,
                ]
            })
            this.toggleCreateTag(false)
        } else {
            onChange && onChange(index, {
                ...bannerInfo,
                bannerList: [
                    ...bannerInfo.bannerList.slice(0, i),
                    values,
                    ...bannerInfo.bannerList.slice(i + 1),
                ]
            })
        }
    }

    deleteSubmit(i) {
        const { onChange, bannerInfo, index } = this.props
        onChange && onChange(index, {
            ...bannerInfo,
            bannerList: [
                ...bannerInfo.bannerList.slice(0, i),
                ...bannerInfo.bannerList.slice(i + 1),
            ]
        })
    }

    render () {
        const { bannerInfo } = this.props
        const { createTag } = this.state
        const names = (bannerInfo.bannerList || []).map(item => item.name)
        return (
            <div className="operation-container ft-clr-d">
                <div className="ft-16 pdb-16 bdb-l">图片轮播</div>
                <div className="mgt-24">
                    <CustomizeDndProvider>
                        { (bannerInfo.bannerList || []).map((banner, index) => {
                            if (!this.bannerRef[banner.name]) {
                                this.bannerRef[banner.name] = React.createRef()
                            }
                            return (
                                <DraggableDiv
                                    key={banner.name}
                                    id={banner.name}
                                    type="bannerList"
                                    dragRef={this.bannerRef[banner.name]}
                                    moveItemFunc={this.sortList.bind(this)}
                                >
                                    <BannerEditInfo
                                        bannerInfo={banner}
                                        index={index}
                                        names={[
                                            ...names.slice(0, index),
                                            ...names.slice(index + 1)
                                        ]}
                                        editSubmit={this.editSubmit.bind(this)}
                                        deleteSubmit={this.deleteSubmit.bind(this)}
                                        dragRef={this.bannerRef[banner.name]}
                                    />
                                </DraggableDiv>
                            )
                        }) }
                    </CustomizeDndProvider>
                    { createTag ? (
                        <BannerEditInfo
                            toggleCreateTag={this.toggleCreateTag.bind(this, false)}
                            index={-1}
                            names={names}
                            editSubmit={this.editSubmit.bind(this)}
                        />
                    ) : null }
                    <Button className="button-large w-100 mgt-16"
                            onClick={this.toggleCreateTag.bind(this, true)}
                            disabled={createTag || bannerInfo.bannerList.length >= 6}
                    >添加广告</Button>
                </div>
            </div>
        )
    }
}

const initBannerInfo = {
    name: '', // 名称
    picture: '', // 图片
    startTime: '', // 开始时间
    endTime: '', // 结束时间
    navType: 'goods-seo', // 跳转类型，取值：NAV_TYPE
    goods: [], // 商品id
    timeRange: {
        startDate: '',
        endDate: '',
    },
}
class BannerEditInfo extends PureComponent {
    static contextType = DesignTemplateContext;

    static propTypes = {
        bannerInfo: PropTypes.object,
        index: PropTypes.number,
        editSubmit: PropTypes.func,
        deleteSubmit: PropTypes.func,
        toggleCreateTag: PropTypes.func,
        names: PropTypes.array,
        dragRef: PropTypes.object
    }

    constructor(props) {
        super(props);
        this.state = {
            isEdit: !props.bannerInfo,
            hackBannerInfo: props.bannerInfo ? {
                ...props.bannerInfo,
                timeRange: {
                    startDate: props.bannerInfo.startTime || '',
                    endDate: props.bannerInfo.endTime || '',
                }
            } : initBannerInfo
        }
        this.formRef = React.createRef()
    }

    toggleEditMode (value) {
        const { bannerInfo, index } = this.props
        this.setState({
            isEdit: value,
            hackBannerInfo: value ? ( bannerInfo ? {
                ...bannerInfo,
                timeRange:{
                    startDate: bannerInfo.startTime || '',
                    endDate: bannerInfo.endTime || '',
                }
            } : initBannerInfo) : this.state.hackBannerInfo
        }, () => {
            if (!value && index < 0) {
                this.props.toggleCreateTag()
            }
        })
    }

    submitForm (values) {
        const { index } = this.props
        this.toggleEditMode(false)
        this.props.editSubmit(values, index)
    }

    handleSubmit () {
        this.formRef.current?.submit()
    }

    deleteSubmit () {
        const { index } = this.props
        this.props.deleteSubmit(index)
    }

    render () {
        const { bannerInfo, index, names, dragRef } = this.props
        const { pStoreId, platformId } = this.context
        const { isEdit, hackBannerInfo } = this.state

        return isEdit ? (
            <div className="operation-block-bg mgt-16 pd-16 pdt-24 pdb-24">
                <Form
                    ref={this.formRef}
                    name="banner-edit"
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}
                    initialValues={hackBannerInfo}
                    requiredMark={false}
                    onFinish={this.submitForm.bind(this)}
                >
                    <Form.Item
                        label='广告标题'
                        name='name'
                        rules={[
                            { required: true, message: '请输入广告标题' },
                            {
                                validator: (_, value) =>
                                    names.includes(value) ? Promise.reject(new Error(`广告标题已存在`)) : Promise.resolve(),
                            }
                        ]}
                        className="mgb-24"
                    >
                        <Input maxLength={5} />
                    </Form.Item>
                    <Form.Item
                        label='广告图片'
                        name='picture'
                        className="mgb-24"
                    >
                        <ImageUpload
                            accept='image/png, image/jpeg, image/jpg'
                            maxFileSize="2m"
                            uploadIntro={(
                                <div className="ft-12 ft-clr-ml mgl-16" style={{width: '140px'}}>
                                    支持PNG、JPG格式，不超过2MB，建议尺寸686*160PX
                                </div>
                            )}
                        />
                    </Form.Item>
                    <Form.Item
                        label='推广时间'
                        name="timeRange"
                        className="mgb-24"
                    >
                        <DateRangePicker />
                    </Form.Item>
                    <Form.Item
                        label='链接'
                        name='navType'
                        className="mgb-24"
                    >
                        <Radio.Group>
                            <Radio value="goods-seo">商品推广</Radio>
                            { platformId === PLATFORM_MAP.wechat && !pStoreId ? (
                                <Radio value="live">直播</Radio>
                            ) : null }
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label=''
                        labelCol={{ span: 0 }}
                        wrapperCol={{ span: 24 }}
                        name='goods'
                        className="mgb-24"
                    >
                        <ProductChoose />
                    </Form.Item>
                    <div className="flex-row-right">
                        <Button className="mgr-16" onClick={this.toggleEditMode.bind(this, false)}>取消</Button>
                        <Button type="primary" onClick={this.handleSubmit.bind(this)}>确定</Button>
                    </div>

                </Form>
            </div>
        ) : ( index < 0 ? null : (
            <div className="flex-row-between operation-block-bg mgt-16 pd-16" ref={dragRef}>
                <div className="flex-vertical-center">
                    <div>{ bannerInfo.name }</div>
                    { bannerInfo.startDate ? (
                        <div>{ bannerInfo.startDate } - { bannerInfo.endDate }</div>
                    ) : null }
                </div>
                <div className="flex-vertical-center">
                    <span className="pdl-8 pdr-8 cur-poi" onClick={this.toggleEditMode.bind(this, true)}>编辑</span>
                    <DoubleCheck title="是否确认删除该广告配置"
                                 onClick={this.deleteSubmit.bind(this)}
                    >
                        <span className="pdl-8 pdr-8 cur-poi bdl-l">删除</span>
                    </DoubleCheck>
                </div>
            </div>
        ))
    }

}

export default BannerListModule

export class BannerListPreview extends PureComponent {
    static propTypes = {
        bannerList: PropTypes.object,
        onClick: PropTypes.func,
        className: PropTypes.string,
    }

    render () {
        const { onClick, bannerInfo, className } = this.props
        let pic = [];
        (bannerInfo.bannerList || []).forEach(banner => {
            banner.picture && pic.push(banner.picture)
        })

        return (
            <div className={`banner-list-preview cur-poi ${className}`} onClick={onClick}>
                { pic.length ? (
                    <img src={pic[0]} alt="" className="banner-img"/>
                ) : (
                    <div className="banner-img empty-bg" />
                ) }
            </div>
        )
    }
}